package com.example.seata.action;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class InventoryServiceImpl implements InventoryService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public boolean tryDecreaseInventory(String productId, int amount) {
        try {
            jdbcTemplate.execute("start transaction ");
            jdbcTemplate.execute("update my_inventory set stock = stock - " + amount + " where productId = " + productId);
            return true;
        }catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean confirmDecreaseInventory(String productId, int amount) {
        try{
            jdbcTemplate.execute("commit ");
            return true;
        }catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean cancelDecreaseInventory(String productId, int amount) {
        try {
            jdbcTemplate.execute("rollback ");
            return true;
        }catch (Exception e) {
            return false;
        }
    }
}
